#include "Socket.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <string>
#include <memory>

using namespace SocketModule;

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}

void GetFromStdin(int *x, int *y, char *oper)
{
    std::cout << "Please Enter x: ";
    std::cin >> *x;
    std::cout << "Please Enter y: ";
    std::cin >> *y;
    std::cout << "Please Enter oper: ";
    std::cin >> *oper;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建客户端套接字
    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildClientSocketMethod();
    // 客户端连接服务器
    int n = client->Connect(server_ip, server_port);
    if (n != 0) // 连接失败
    {
        // 那么我们连接不上服务端，客户端直接退出吧
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    std::string resp_buffer;
    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    // 连接服务器成功
    while (true)
    {
        // 1.我们这里直接从标准输入（键盘）中获取x,y,oper数据
        int x, y;
        char oper;
        GetFromStdin(&x, &y, &oper);

        // 2.构建一个请求，要的是可以直接发送的字符串
        std::string req_str = protocol->BuildRequestString(x, y, oper);
        std::cout << "----------encode req string-----------" << std::endl;
        std::cout << req_str << std::endl;
        std::cout << "--------------------------------------" << std::endl;

        // 3.发送请求
        client->Send(req_str);

        // 4.获取应答
        Response resp;
        bool n = protocol->GetResponse(client, resp_buffer, &resp);
        if (n == false)
        {
            // 读取失败
            break;
        }
        // 显示一下结果
        resp.ShowResult();
    }

    client->Close();
    return 0;
}